package isis.boutrytogni;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.*;

@SuppressWarnings("serial")
public class SendMailMessage extends HttpServlet {
	String adminAddress = "olivia.togni@gmail.com";
	String adminName = "olivia";

	public void doGet(HttpServletRequest req, HttpServletResponse response) throws IOException {

		response.setContentType("text/html");
		PrintWriter page = response.getWriter();

		page.println("<body>");

		// Les infos du message sont passées en paramètres à la servlet
		String recipient = req.getParameter("recipient");
		if (recipient != null) {
			String sendResult = "Could not send message";
			String messageBody = req.getParameter("messageBody");
			if (messageBody == null)
				messageBody = "Message vide";
			String subject = req.getParameter("subject");
			if (subject == null)
				subject = "No subject";
			Properties props = new Properties();
			Session session = Session.getDefaultInstance(props, null);

			try {
				Message msg = new MimeMessage(session);
				msg.setFrom(new InternetAddress(adminAddress, adminName));
				msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient, "Mr. User"));
				msg.setSubject(subject);
				msg.setText(messageBody);
				Transport.send(msg);
				sendResult = "Message sent OK";

			} catch (AddressException e) {
				sendResult = e.getMessage();
			} catch (MessagingException e) {
				sendResult = e.getMessage();
			}
			page.printf("<h2>%s</h2>", sendResult);
		}

		showMailForm(page);

		page.println("<p><a href=..>Retour au menu</a></p>");
		page.println("</body>");
	}

	private void showMailForm(PrintWriter page) {
		page.println("<form>");
		page.println("<h2>Send Email</h2>");
		page.printf("from : <input disabled value=%s><br>", adminAddress);
		page.println("to : <input name=recipient><br>");
		page.println("subject : <input name=subject><br>");
		page.println("message :<br><textarea name=messageBody rows=10 cols=80></textarea><br>");
		page.println("<input type=submit>");
		page.println("</form>");
	}
}